package com.shuai.user.controller;

import com.shuai.common.constant.ErrorCode;
import com.shuai.common.exception.BusinessException;
import com.shuai.common.rps.BaseResponse;
import com.shuai.common.utils.ResultUtils;
import com.shuai.user.service.CaptchaService;
import com.shuai.user.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.io.IOException;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/verify")
@Slf4j
@Validated
public class VerifyController {

    @Autowired
    private EmailService emailService;

    @Autowired
    private CaptchaService captchaService;

    @GetMapping("/send_email")
    public BaseResponse<Boolean> sendEmailCode(@Valid
                                               @NotNull(message = "邮箱不能为空")
                                               @Pattern(regexp = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$", message = "邮箱格式不正确")
                                               String email) {
        try {
            emailService.sendCodeToUser(email);
        } catch (MessagingException e) {
            log.error("\n\n" + LocalDateTime.now() + "[发送邮箱验证码失败，接收人:{}]", email);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "发送失败");
        }
        return ResultUtils.success(Boolean.TRUE);
    }

    @GetMapping("/captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        captchaService.sendCaptcha(request, response);
    }
}
